﻿using Commons.ASPNETCore;
using Commons.DomainBase;
using IdentityService.Domain;
using IdentityService.Webapi.Controllers.UserAdmin;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using Org.BouncyCastle.Ocsp;
using System.IO;
using System.Security.Claims;

namespace IdentityService.Webapi.Controllers
{
    [Route("Identity/[controller]")]
  //  [Authorize]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IIdRepository repository;

        public UserController(IIdRepository repository)
        {
            this.repository = repository;
        }

        [HttpGet("Info")] 
        public async Task<Result> GetUserInfo()
        {
            string userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
            string role = this.User.FindFirstValue(ClaimTypes.Role);
            var user = await repository.FindByIdAsync(long.Parse(userId));
            if (user == null)//可能用户注销了
            {
                return Result.Fail(CodeType.NO_DATA);
            }
            //出于安全考虑，不要机密信息传递到客户端
            //除非确认没问题，否则尽量不要直接把实体类对象返回给前端
            return Result.Success( new { user.UserName, role });
        }

        [HttpGet("Role")]
        public Result GetRole()
        {
            string role = this.User.FindFirstValue(ClaimTypes.Role);
            return Result.Success( new { role });
        }

        /// <summary>
        /// 获取子列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("List")]
        public Result FindAllUser()
        {
            var list = repository.FindAllUsers(long.Parse(this.User.FindFirstValue(ClaimTypes.NameIdentifier)));
            
          //  list.Where(u => new[] { 1, 2, 3 }.Contains(u.Id))
            if (list == null)
            {
                return Result.Success(response: new List<User>());
            }
            return Result.Success(list.Select(x => new { x.UserName, x.Name, x.Id }));
        }

        /// <summary>
        /// 获取子列表 
        /// </summary>
        /// <returns></returns>
        [HttpPost("ListIn")]
        public Result FindUserByIdList([FromBody] long[] IdList)
        {
            var list = repository.FindAllUsers(long.Parse(this.User.FindFirstValue(ClaimTypes.NameIdentifier)));

            if (list == null)
            {
                return Result.Success(response: new List<User>());
            }
            return Result.Success(list.Where(u => IdList.Contains(u.Id)).Select(x => new { x.UserName, x.Name, x.Id }));
        }



        /// <summary>
        /// 获取子列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("PageList")]
        public Result FindAllUserPage([FromQuery] PageRequest page)
        {
            var list = repository.FindAllUserPage(long.Parse(this.User.FindFirstValue(ClaimTypes.NameIdentifier)),page.PageIndex,page.PageSize);
            if (list == null)
            {
                return Result.Success(response: new List<User>());
            }
            return Result.Success(list);
        }
        /// <summary>
        /// 添加老师
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [Authorize(Roles = "admin")]
        [HttpPost(template: "Teacher")]
        public async Task<Result> AddTeacherUser(AddTeacherUserRequest req)
        {

            User? u = await repository.FindByNameAsync(req.UserName);
            if (u != null)
            {
                return Result.Fail(CodeType.HAVE_DATA);
            }

            u = IdentityService.Domain.User.Create( req.UserName, req.Password);
            u.CreateUserId = long.Parse(this.User.FindFirstValue(ClaimTypes.NameIdentifier));
            u.Name = req.Name;
            (var result, User user, var password) = await repository.AddUserAsync(u, "Teacher");
            if (!result)
            {
                return Result.Fail();
            }
            return Result.Success();
        }

        /// <summary>
        /// 添加老师
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [Authorize(Roles = "Teacher")]
        [HttpPost(template: "Student")]
        public async Task<Result> AddStudentUser(AddTeacherUserRequest req)
        {

            User? u = await repository.FindByNameAsync(req.UserName);
            if (u != null)
            {
                return Result.Fail(CodeType.HAVE_DATA);
            }

            u = IdentityService.Domain.User.Create(req.UserName, req.Password);
            u.CreateUserId = long.Parse(this.User.FindFirstValue(ClaimTypes.NameIdentifier));
            u.Name = req.Name;
            (var result, User user, var password) = await repository.AddUserAsync(u, "Student");
            if (!result)
            {
                return Result.Fail();
            }
            return Result.Success();
        }

        

        /// <summary>
        /// 获取学生
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // 获取特定老师
        [HttpGet("Teacher/{id}")]
        public async Task<Result> GetTeacher(int id)
        {
            var teacher = await repository.FindByIdAsync(id);
            if (teacher == null)
            {
                return Result.Fail(CodeType.NO_DATA);
            }
            return Result.Success(teacher);
        }


        /// <summary>
        /// 添加管理员
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [Authorize(Roles = "Admin")]
        [HttpPost(template: "Admin")]
        public async Task<Result> AddAdminUser(AddAdminUserRequest req)
        {

            User u = IdentityService.Domain.User.Create(req.UserName, "123456");
            u.CreateUserId = long.Parse(this.User.FindFirstValue(ClaimTypes.NameIdentifier));
            u.Name = req.UserName;
            (var result, User user, var password) = await repository.AddUserAsync(u,"Admin");
            if (!result)
            {
                return Result.Fail();
            }
            return Result.Success();
        }

        /// <summary>
        /// 获取admin信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("Admin/{id}")]
        public async Task<Result> GetAdmin(int id)
        {
            var admin = await repository.FindByIdAsync(id);
            if (admin == null)
            {
                return Result.Fail(CodeType.NO_DATA);
            }
            return Result.Success(admin);
        }

        [HttpPost("import")]
        public async Task<Result> ImportUsers(IFormFile file)
        {
            long userId = long.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));
            List<IdentityService.Domain.User> outList = new List<IdentityService.Domain.User>();

            if (file == null || file.Length == 0)
            {
                return Result.Fail(CodeType.NO_FILE);
            }

            try
            {
                using var stream = file.OpenReadStream();
                IEnumerable<dynamic> rows = stream.Query(useHeaderRow: true, excelType: ExcelType.XLSX).ToList();

                foreach (var row in rows)
                {
                    if (string.IsNullOrEmpty(row.登录名?.ToString()))
                    {
                        continue; // Skip rows with empty login names
                    }

                    var user = CreateUserFromRow(row, userId);
                    if (user != null)
                    {
                        outList.Add(user);
                    }
                }

                // Save users to database
                // _context.Users.AddRange(outList);
                // await _context.SaveChangesAsync();

                return Result.Success(outList);
            }
            catch (Exception ex)
            {

                return Result.Fail();
            }
        }


        private IdentityService.Domain.User? CreateUserFromRow(dynamic row, long userId)
        {
            string loginName = row.登录名?.ToString() ?? string.Empty;
            string password = row.密码?.ToString() ?? "123456";
            string name = row.姓名?.ToString() ?? string.Empty;

            if (string.IsNullOrEmpty(loginName))
            {
                return null; // Skip if login name is empty
            }

            var user = IdentityService.Domain.User.Create(loginName, password);
            user.CreateUserId = userId;
            user.Name = name;
            return user;
        }
    }
}
